package com.jfinal.j2cache.plugin.j2cache;

import net.oschina.j2cache.CacheChannel;
import net.oschina.j2cache.CacheProviderHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

public class J2CacheKit {

    private static volatile CacheChannel cacheChannel;

    static void init(CacheChannel cacheChannel) {
        J2CacheKit.cacheChannel = cacheChannel;
    }

    public static void put(String cacheName, String key, Object value) {
        cacheChannel.set(cacheName, key, value);
    }

    public static <T> T get(String cacheName, String key) {
        return (T) cacheChannel.get(cacheName, key).getValue();
    }

    public static <E> List<E> get(String cacheName) {
        List<E> valueList = new ArrayList<>();
        Set<String> keys = (Set<String>) cacheChannel.keys(cacheName);
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                valueList.add(get(cacheName, key));
            }
        }
        return valueList;
    }

    public static void remove(String cacheName, String key) {
        cacheChannel.evict(cacheName, key);
    }

    public static void removeAll(String cacheName) {
        CacheProviderHolder.getL1Provider().removeCache(cacheName);
        CacheProviderHolder.getL2Provider().removeCache(cacheName);
    }
}
